/*
	Programmers: Martin Bakiev & David Visco
	Date: 04/04/2010
	Homework #3
	VC:
		Simple version control system that supports checkin, checkout,
		diff and log.
		checkin - checks in a file
		checkout - checks out a file
		diff - creates a patch file between 2 version of the file
		log - shows log of activity with file
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utility.h"

extern int errno;

int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		printf("Consult documentation for the correct use of this program.\n");
		return 0;
	}

	if(strcmp(argv[1], "checkin") == 0)
	{
		if(fileExists(argv[2]))
		{
			if(isFileVersioned(argv[2]))
			{
				//Already versioned, UPDATE VERSION
				int version =  checkIn(argv[2]);
				if(version == 0)
					printf("You can only check in a file if you check it out first.\n");
				else
					printf("\n%s at version: %d.\n", argv[2], version);
			}
			else
			{
				//Add to version control
				if(!firstCheckin(argv[2]))
					printf("Could not checkin file.\n");
				else
					printf("\n%s at version 1.\n", argv[2]);
			}
		}
		else
			printf("File \"%s\" does not exist.\n", argv[2]);
	}
	else if(strcmp(argv[1], "checkout") == 0)
	{
		//PERFORM CHECKOUT
		if(isFileVersioned(argv[2]))
		{
			int version = checkOut(argv[2]);

			if(version > 0)
				printf("%s version %d checked out.\n", argv[2], version);
			else
				printf("You can only checkout a file once and if no one else has a lock on it.\n");
		}
		else
		{
			printf("%s is not versioned.\n", argv[2]);
		}
	}
	else if(strcmp(argv[1], "read") == 0 &&  argc == 4)
	{
		//PERFORM  READ
		if(isFileVersioned(argv[2]))
		{
			int version = atoi(argv[3]);
			if(version > 0)
			{
				version = getFileVersion(argv[2], version, argv[2]);
				if(version)
					printf("Read-Only copy of version %d obtained.\n", version);
				else
					printf("Invalid version number.\n");
			}
			else
				printf("Invalid version number.\n");
		}
		else
			printf("%s is not version controlled by us.\n", argv[2]);
	}
	else if(strcmp(argv[1], "diff") == 0 && argc == 5)
	{
		//PERFORM DIFF
		if(isFileVersioned(argv[2]))
		{
			int v1 = atoi(argv[3]);
			int v2 = atoi(argv[4]);

			if(!printPatch(argv[2], v1, v2))
				printf("Could not generate patch.\n");
		}
		else
		{
			printf("%s is not versioned.\n", argv[2]);
		}

	}
	else if(strcmp(argv[1], "log") == 0)
	{
		//PERFORM log
		if(isFileVersioned(argv[2]))
		{
			printLog(argv[2]);
		}
		else
		{
			printf("%s is not versioned.\n", argv[2]);
		}

	}
	else
	{
		printf("Uknown command, consult documentation.\n");
	}
	
	return 0;
}
